<template>
  <div class="consultant-management">
    <!-- 页面标题和操作按钮 -->
    <VCard class="mb-4">
      <VCardTitle class="d-flex align-center justify-space-between">
        <div class="d-flex align-center">
          <VIcon icon="mdi-account-tie" size="32" color="primary" class="mr-3" />
          <span class="text-h5">咨询师信息管理</span>
        </div>
        <VBtn color="primary" @click="showAddDialog" prepend-icon="mdi-plus">
          添加咨询师
        </VBtn>
      </VCardTitle>
    </VCard>

    <!-- 咨询师卡片网格 -->
    <VRow>
      <VCol 
        v-for="consultant in consultants" 
        :key="consultant.id" 
        cols="12" 
        sm="6" 
        md="4" 
        lg="3"
      >
        <VCard class="consultant-card" elevation="2" hover>
          <!-- 头像区域 -->
          <div class="avatar-container" @click="selectImage(consultant)">
            <VAvatar 
              size="120" 
              class="consultant-avatar"
            >
              <VImg 
                v-if="consultant.avatar && consultant.avatar.startsWith('data:image')" 
                :src="consultant.avatar"
                alt="咨询师头像"
                width="120"
                height="120"
                cover
              />
              <VImg 
                v-else-if="consultant.avatar && !consultant.avatar.startsWith('data:image')" 
                :src="consultant.avatar"
                alt="咨询师头像"
                width="120"
                height="120"
                cover
              />
              <VImg 
                v-else 
                :src="defaultAvatar"
                alt="默认头像"
                width="120"
                height="120"
                cover
              />
            </VAvatar>
            <div class="avatar-overlay">
              <VIcon icon="mdi-camera" color="white" size="24" />
              <div class="text-caption text-white mt-1">点击更换</div>
            </div>
          </div>

          <VCardText class="text-center">
            <!-- 基本信息 -->
            <h3 class="text-h6 mb-2">{{ consultant.name }}</h3>
            <VChip 
              :color="getStatusColor(consultant.is_active)" 
              size="small" 
              class="mb-2"
            >
              {{ consultant.is_active ? '在职' : '离职' }}
            </VChip>
            
            <!-- 详细信息 -->
            <div class="consultant-info">
              <div class="info-item">
                <VIcon icon="mdi-card-account-details" size="16" class="mr-1" />
                <span>{{ consultant.title || '心理咨询师' }}</span>
              </div>
              <div class="info-item">
                <VIcon icon="mdi-school" size="16" class="mr-1" />
                <span>{{ consultant.qualification || '国家二级心理咨询师' }}</span>
              </div>
              <div class="info-item">
                <VIcon icon="mdi-heart" size="16" class="mr-1" />
                <span>{{ consultant.specialty || '综合心理咨询' }}</span>
              </div>
              <div class="info-item">
                <VIcon icon="mdi-phone" size="16" class="mr-1" />
                <span>{{ consultant.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <VIcon icon="mdi-email" size="16" class="mr-1" />
                <span>{{ consultant.username }}</span>
              </div>
            </div>

            <!-- 描述 -->
            <div v-if="consultant.description" class="consultant-description">
              <VDivider class="my-3" />
              <p class="text-body-2">{{ consultant.description }}</p>
            </div>
          </VCardText>

          <!-- 操作按钮 -->
          <VCardActions>
            <VBtn 
              variant="text" 
              color="primary" 
              @click="editConsultant(consultant)"
              prepend-icon="mdi-pencil"
            >
              编辑
            </VBtn>
            <VSpacer />
            <VBtn 
              variant="text" 
              :color="consultant.is_active ? 'error' : 'success'"
              @click="toggleConsultantStatus(consultant)"
              :prepend-icon="consultant.is_active ? 'mdi-account-off' : 'mdi-account-check'"
            >
              {{ consultant.is_active ? '停用' : '启用' }}
            </VBtn>
          </VCardActions>
        </VCard>
      </VCol>
    </VRow>

    <!-- 空状态 -->
    <VCard v-if="consultants.length === 0" class="text-center py-8">
      <VIcon icon="mdi-account-search" size="64" color="grey" />
      <VCardTitle>暂无咨询师信息</VCardTitle>
      <VCardText>点击上方"添加咨询师"按钮添加第一位咨询师</VCardText>
    </VCard>

    <!-- 添加/编辑咨询师对话框 -->
    <VDialog v-model="showDialog" max-width="600px" @keydown.esc="showDialog = false" @click:outside="showDialog = false">
      <VCard>
        <VCardTitle class="d-flex align-center">
          <VIcon :icon="isEditing ? 'mdi-pencil' : 'mdi-plus'" class="mr-2" />
          {{ isEditing ? '编辑咨询师信息' : '添加咨询师' }}
        </VCardTitle>
        
        <VCardText>
          <VForm ref="formRef" v-model="formValid">
            <VRow>
              <!-- 头像预览 -->
              <VCol cols="12" class="text-center">
                <div class="avatar-preview" @click="selectImageForForm">
                  <VAvatar 
                    size="100" 
                    class="mb-2"
                  >
                    <VImg 
                      v-if="formData.avatar && formData.avatar.startsWith('data:image')" 
                      :src="formData.avatar"
                      alt="头像预览"
                      width="100"
                      height="100"
                      cover
                    />
                    <VImg 
                      v-else-if="formData.avatar && !formData.avatar.startsWith('data:image')" 
                      :src="formData.avatar"
                      alt="头像预览"
                      width="100"
                      height="100"
                      cover
                    />
                    <VImg 
                      v-else 
                      :src="defaultAvatar"
                      alt="默认头像"
                      width="100"
                      height="100"
                      cover
                    />
                  </VAvatar>
                  <div class="text-caption">点击选择头像</div>
                </div>
              </VCol>

              <!-- 基本信息 -->
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="formData.name"
                  label="姓名 *"
                  :rules="[rules.required]"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="formData.username"
                  label="用户名 *"
                  :rules="[rules.required]"
                  variant="outlined"
                  :readonly="isEditing"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="formData.phone"
                  label="联系电话"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VSelect
                  v-model="formData.gender"
                  :items="genderOptions"
                  label="性别"
                  variant="outlined"
                />
              </VCol>

              <!-- 专业信息 -->
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="formData.title"
                  label="职称"
                  placeholder="如：资深心理咨询师"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12" sm="6">
                <VTextField
                  v-model="formData.qualification"
                  label="资格证书"
                  placeholder="如：国家二级心理咨询师"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12">
                <VTextField
                  v-model="formData.specialty"
                  label="专业方向"
                  placeholder="如：抑郁症、焦虑症、人际关系"
                  variant="outlined"
                />
              </VCol>
              <VCol cols="12">
                <VTextarea
                  v-model="formData.description"
                  label="个人简介"
                  placeholder="请输入咨询师的个人简介和专业背景..."
                  variant="outlined"
                  rows="3"
                />
              </VCol>

              <!-- 状态 -->
              <VCol cols="12">
                <VSwitch
                  v-model="formData.is_active"
                  label="是否在职"
                  color="primary"
                  hide-details
                />
              </VCol>
            </VRow>
          </VForm>
        </VCardText>

        <VCardActions>
          <VSpacer />
          <VBtn color="secondary" @click="closeDialog">取消</VBtn>
          <VBtn 
            color="primary" 
            @click="saveConsultant"
            :loading="saving"
            :disabled="!formValid"
          >
            {{ isEditing ? '更新' : '添加' }}
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import { useNotificationStore } from '@/store/notificationStore';
import { fetchUserList, updateUser, createUser } from '@/api/user';

const snackbarStore = useSnackbarStore();
const notificationStore = useNotificationStore();

// 响应式数据
const consultants = ref<any[]>([]);
const showDialog = ref(false);
const isEditing = ref(false);
const saving = ref(false);
const formValid = ref(false);
const formRef = ref();
const fileInput = ref();
const currentConsultant = ref<any>(null);

// 默认头像
const defaultAvatar = '/assets/images/avatars/avatar-1.png';

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  username: '',
  phone: '',
  gender: 'M',
  title: '',
  qualification: '',
  specialty: '',
  description: '',
  avatar: '',
  is_active: true
});

// 选项数据
const genderOptions = [
  { title: '男', value: 'M' },
  { title: '女', value: 'F' }
];

// 验证规则
const rules = {
  required: (v: string) => !!v || '此项为必填项'
};

// 方法
const loadConsultants = async () => {
  try {
    const response = await fetchUserList();
    console.log('API响应:', response);
    
    let userData = [];
    if (response.data && response.data.success && response.data.data) {
      userData = response.data.data;
    } else if (response.data && Array.isArray(response.data)) {
      userData = response.data;
    } else {
      console.error('无效的API响应格式:', response);
      snackbarStore.showMessage('API响应格式错误');
      return;
    }
    
    // 只获取咨询师角色的用户
    consultants.value = userData.filter(user => user.role === 'CONSULTANT');
    
    // 解析额外信息
    consultants.value.forEach(consultant => {
      try {
        const extraInfo = typeof consultant.extra_info === 'string' 
          ? JSON.parse(consultant.extra_info) 
          : consultant.extra_info || {};
        
        consultant.title = extraInfo.title || '心理咨询师';
        consultant.qualification = extraInfo.qualification || '国家二级心理咨询师';
        consultant.specialty = extraInfo.specialty || '综合心理咨询';
        consultant.description = extraInfo.description || '';
        consultant.avatar = extraInfo.avatar || '';
        
        // 添加调试信息
        console.log(`咨询师 ${consultant.name} 的信息:`, {
          hasExtraInfo: !!consultant.extra_info,
          hasAvatar: !!consultant.avatar,
          title: consultant.title,
          qualification: consultant.qualification
        });
      } catch (e) {
        console.error('解析咨询师额外信息失败:', e, consultant);
      }
    });
    
    console.log('加载到的咨询师数量:', consultants.value.length);
  } catch (error) {
    console.error('加载咨询师列表失败:', error);
    snackbarStore.showMessage('加载咨询师列表失败: ' + error.message);
  }
};

const getStatusColor = (isActive: boolean) => {
  return isActive ? 'success' : 'error';
};

const showAddDialog = () => {
  isEditing.value = false;
  resetForm();
  showDialog.value = true;
};

const editConsultant = (consultant: any) => {
  isEditing.value = true;
  currentConsultant.value = consultant;
  
  // 填充表单数据
  formData.id = consultant.id;
  formData.name = consultant.name;
  formData.username = consultant.username;
  formData.phone = consultant.phone || '';
  formData.gender = consultant.gender || 'M';
  formData.title = consultant.title || '';
  formData.qualification = consultant.qualification || '';
  formData.specialty = consultant.specialty || '';
  formData.description = consultant.description || '';
  formData.avatar = consultant.avatar || '';
  formData.is_active = consultant.is_active;
  
  showDialog.value = true;
};

const resetForm = () => {
  formData.id = null;
  formData.name = '';
  formData.username = '';
  formData.phone = '';
  formData.gender = 'M';
  formData.title = '';
  formData.qualification = '';
  formData.specialty = '';
  formData.description = '';
  formData.avatar = '';
  formData.is_active = true;
  currentConsultant.value = null;
};

const closeDialog = () => {
  showDialog.value = false;
  resetForm();
};

const saveConsultant = async () => {
  if (!formRef.value.validate()) return;
  
  saving.value = true;
  try {
    // 构建额外信息
    const extraInfo = {
      title: formData.title,
      qualification: formData.qualification,
      specialty: formData.specialty,
      description: formData.description,
      avatar: formData.avatar
    };

    const updateData = {
      username: formData.username,
      name: formData.name,
      phone: formData.phone,
      gender: formData.gender,
      role: 'CONSULTANT',
      is_active: formData.is_active,
      extra_info: JSON.stringify(extraInfo)
    };

    if (isEditing.value) {
      // 更新现有咨询师
      const response = await updateUser(formData.id, updateData);
      if (response.data && (response.data.success || response.data.code === 200)) {
        snackbarStore.showMessage('咨询师信息更新成功');
        notificationStore.addUserNotification(
          `咨询师 ${formData.name} 的信息已更新`,
          formData.avatar,
          '/consultant-management'
        );
      } else {
        throw new Error(response.data?.message || '更新失败');
      }
    } else {
      // 添加新咨询师
      const response = await createUser(updateData);
      if (response.data && (response.data.success || response.data.code === 200)) {
        snackbarStore.showMessage('咨询师添加成功');
        notificationStore.addUserNotification(
          `咨询师 ${formData.name} 已添加`,
          formData.avatar,
          '/consultant-management'
        );
      } else {
        throw new Error(response.data?.message || '添加失败');
      }
    }

    closeDialog();
    loadConsultants();
  } catch (error) {
    console.error('保存咨询师信息失败:', error);
    snackbarStore.showMessage('保存失败：' + error.message);
  } finally {
    saving.value = false;
  }
};

const toggleConsultantStatus = async (consultant: any) => {
  try {
    const extraInfo = {
      title: consultant.title,
      qualification: consultant.qualification,
      specialty: consultant.specialty,
      description: consultant.description,
      avatar: consultant.avatar
    };

    const updateData = {
      username: consultant.username,
      name: consultant.name,
      phone: consultant.phone,
      gender: consultant.gender,
      role: consultant.role,
      is_active: !consultant.is_active,
      extra_info: JSON.stringify(extraInfo)
    };

    const response = await updateUser(consultant.id, updateData);
    if (response.data && (response.data.success || response.data.code === 200)) {
      const status = consultant.is_active ? '停用' : '启用';
      snackbarStore.showMessage(`咨询师 ${consultant.name} 已${status}`);
      notificationStore.addSystemNotification(
        `咨询师 ${consultant.name} 已被${status}`,
        '/consultant-management'
      );
      loadConsultants();
    } else {
      throw new Error(response.data?.message || '操作失败');
    }
  } catch (error) {
    console.error('切换咨询师状态失败:', error);
    snackbarStore.showMessage('操作失败：' + error.message);
  }
};

const selectImage = (consultant: any) => {
  currentConsultant.value = consultant;
  fileInput.value?.click();
};

const selectImageForForm = () => {
  currentConsultant.value = null;
  fileInput.value?.click();
};

const handleImageSelect = (event: any) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    snackbarStore.showMessage('请选择图片文件');
    return;
  }

  // 验证文件大小 (限制5MB)
  if (file.size > 5 * 1024 * 1024) {
    snackbarStore.showMessage('图片文件大小不能超过5MB');
    return;
  }

  // 读取文件并转换为Base64
  const reader = new FileReader();
  reader.onload = (e) => {
    const base64 = e.target?.result as string;
    
    if (currentConsultant.value) {
      // 直接更新咨询师头像
      updateConsultantAvatar(currentConsultant.value, base64);
    } else {
      // 更新表单中的头像
      formData.avatar = base64;
    }
  };
  reader.readAsDataURL(file);
  
  // 清空文件输入
  event.target.value = '';
};

const updateConsultantAvatar = async (consultant: any, avatar: string) => {
  try {
    const extraInfo = {
      title: consultant.title,
      qualification: consultant.qualification,
      specialty: consultant.specialty,
      description: consultant.description,
      avatar: avatar
    };

    const updateData = {
      username: consultant.username,
      name: consultant.name,
      phone: consultant.phone,
      gender: consultant.gender,
      role: consultant.role,
      is_active: consultant.is_active,
      extra_info: JSON.stringify(extraInfo)
    };

    const response = await updateUser(consultant.id, updateData);
    if (response.data && (response.data.success || response.data.code === 200)) {
      snackbarStore.showMessage('头像更新成功');
      loadConsultants();
    } else {
      throw new Error(response.data?.message || '更新失败');
    }
  } catch (error) {
    console.error('更新头像失败:', error);
    snackbarStore.showMessage('头像更新失败：' + error.message);
  }
};

// 生命周期
onMounted(() => {
  loadConsultants();
});
</script>

<style scoped>
.consultant-management {
  padding: 20px;
}

.consultant-card {
  transition: transform 0.2s, box-shadow 0.2s;
  height: 100%;
}

.consultant-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.15) !important;
}

.avatar-container {
  position: relative;
  display: flex;
  justify-content: center;
  padding: 20px;
  cursor: pointer;
}

.consultant-avatar {
  transition: transform 0.2s;
}

.avatar-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,0.6);
  border-radius: 50%;
  width: 120px;
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-container:hover .consultant-avatar {
  transform: scale(1.05);
}

.consultant-info {
  text-align: left;
  margin-top: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.consultant-description {
  text-align: left;
}

.avatar-preview {
  cursor: pointer;
  transition: transform 0.2s;
}

.avatar-preview:hover {
  transform: scale(1.05);
}
</style> 